#!/bin/bash
# V2ray订阅链接自动获取脚本安装程序

set -e

echo "=== V2ray订阅链接自动获取脚本安装程序 ==="

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用sudo运行此脚本"
    exit 1
fi

# 检查Python3是否安装
if ! command -v python3 &> /dev/null; then
    echo "错误: Python3未安装，请先安装Python3"
    exit 1
fi

# 检查pip3是否安装
if ! command -v pip3 &> /dev/null; then
    echo "错误: pip3未安装，请先安装pip3"
    exit 1
fi

echo "1. 安装Python依赖..."
pip3 install -r requirements.txt

echo "2. 设置脚本权限..."
chmod +x proxy_fetcher.py
chmod +x cron_setup.sh

echo "3. 创建必要的目录..."
# 从Python配置文件中读取配置（如果存在）
if [ -f "config.py" ]; then
    echo "检测到配置文件，读取配置..."
    OUTPUT_DIR=$(python3 -c "import config; import os; print(os.path.expanduser(config.OUTPUT_DIR))" 2>/dev/null || echo "/var/proxy")
    LOG_FILE=$(python3 -c "import config; import os; print(os.path.expanduser(config.LOG_FILE))" 2>/dev/null || echo "/var/log/proxy_fetcher.log")
    OUTPUT_PERM=$(python3 -c "import config; print(oct(config.OUTPUT_DIR_PERMISSIONS)[2:])" 2>/dev/null || echo "755")
    LOG_PERM=$(python3 -c "import config; print(oct(config.LOG_FILE_PERMISSIONS)[2:])" 2>/dev/null || echo "644")
else
    echo "使用默认配置..."
    OUTPUT_DIR="/var/proxy"
    LOG_FILE="/var/log/proxy_fetcher.log"
    OUTPUT_PERM="755"
    LOG_PERM="644"
fi

mkdir -p "$OUTPUT_DIR"
chmod "$OUTPUT_PERM" "$OUTPUT_DIR"

LOG_DIR=$(dirname "$LOG_FILE")
mkdir -p "$LOG_DIR"
touch "$LOG_FILE"
chmod "$LOG_PERM" "$LOG_FILE"

echo "4. 配置cron任务..."
./cron_setup.sh

echo "5. 测试脚本..."
echo "正在测试脚本..."
if python3 proxy_fetcher.py; then
    echo "测试成功！"
else
    echo "测试失败，请检查日志文件: /var/log/proxy_fetcher.log"
    exit 1
fi

echo ""
echo "=== 安装完成 ==="
echo "脚本已安装并配置完成"
echo "输出目录: $OUTPUT_DIR"
echo "日志文件: $LOG_FILE"
echo "执行时间: 每天凌晨2点"
echo ""
echo "手动执行命令: python3 proxy_fetcher.py"
echo "查看日志命令: tail -f /var/log/proxy_fetcher.log"
echo "查看cron任务: crontab -l"
